package com.fh.shop.api.sms.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fh.shop.api.common.Constant;
import com.fh.shop.api.common.ResponseEnum;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.sms.vo.SMSVo;
import com.fh.shop.api.util.KeyUtil;
import com.fh.shop.api.util.RedisUtil;
import com.fh.shop.api.util.RegUtil;
import com.fh.shop.api.util.SMSCodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service("smsService")
public class ISMSServiceImpl implements ISMSService {
    @Override
    public ServerResponse smsCode(String phone) {
        //判断手机号为空
        if (StringUtils.isEmpty(phone)){
           return ServerResponse.error(ResponseEnum.PHONE_IS_NULL);
        }
        //判断手机号是否正确
        if (!RegUtil.isPhone(phone)){
            return ServerResponse.error(ResponseEnum.MEMBER_PHONE_ERROR);
        }
        //获取验证码等所有信息的json字符串
        String smsCodeJson = SMSCodeUtil.smsCode(phone);
        //使用第三方工具转换为java对象
        SMSVo smsVo = JSON.parseObject(smsCodeJson, SMSVo.class);
        if (smsVo.getCode() != Constant.CODE_SUCCESS){
            return ServerResponse.error(Constant.CODE_ERROR,"您的验证码发送失败,出现异常:"+smsVo.getCode()+",请练习管理员");
        }
        //获取里面的验证码
        String code = smsVo.getObj();
        //放入缓存中 并且设置过期时间
        RedisUtil.setex(KeyUtil.regCodeKey(phone),code,Constant.CODE_EXPIRATION);
        return ServerResponse.success(smsVo);
    }
}
